package com.xr.test;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.junit.Test;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class testFreemarker {

    @Test
    public void test() throws IOException, TemplateException {
        //1.创建configuration对象
        Configuration configuration = new Configuration(Configuration.getVersion());
        //2.设置模板文件所在的目录
        configuration.setDirectoryForTemplateLoading(new File("e:\\ftl"));
        //3.设置字符集
        configuration.setDefaultEncoding("utf-8");
        //前面的和spring整合之后，都不用做

        //4.创建一个模板对象
        Template template=configuration.getTemplate("test.ftl");
        //5.准备数据，map
        Map map=new HashMap();
        map.put("name","小强");
        map.put("message","欢迎来到freeMarker的世界!");
        map.put("success",false);
        List goodsList=new ArrayList();

        Map goods1=new HashMap();
        goods1.put("name", "苹果");
        goods1.put("price", 5.8);

        Map goods2=new HashMap();
        goods2.put("name", "香蕉");
        goods2.put("price", 2.5);

        Map goods3=new HashMap();
        goods3.put("name", "橘子");
        goods3.put("price", 3.2);

        goodsList.add(goods1);
        goodsList.add(goods2);
        goodsList.add(goods3);

        map.put("goodsList", goodsList);
        //6.创建writer
        FileWriter out = new FileWriter(new File("e:\\ftl\\test.html"));
        //7.输出
        template.process(map,out);
        //8.关流
        out.close();
    }
}
